# -*- encoding=UTF-8 -*-
import json
import time
from time import sleep

import requests
import uiautomator2 as u1


class monitor:

    def __init__(self, devices_name, packageName):
        self.log_path = time.strftime("Monitor_%Y_%m_%d_%H_%M_%S", time.localtime()) + '.log'
        self.packageName = packageName
        self.d = u1.connect(devices_name)
        self.d.unlock()
        self.d.press("home")

    def set_up(self):
        self.d.app_stop(self.packageName)
        sleep(1)
        self.d.app_start(self.packageName)
        gotimes = 0
        while True:
            if self.d(text="首页").exists:
                sleep(3)
                break
            else:
                sleep(3)
                gotimes += 1
            if gotimes == 4:
                break

    def write_log(self, file_path, str):
        '''
        报告录入工具
        :param str: 字符串
        :return: None
        '''
        if file_path is not None:
            t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            with open(file_path, "a") as file:
                file.write(t + " " + str + "\n")
                file.close()

    def test_down(self):
        for quit_n in range(2):
            sleep(1)
            if self.d(text="首页").exists:
                break
            else:
                self.d.press("back")
        self.d.app_stop(self.packageName)

    def start_monitor(self, test_num):
        sleep(3)
        try:
            self.d(resourceId="com.heytap.smarthome:id/iv_company").click(timeout=5)
            start_time = time.time()

            dingTalk = DingMessage()

            is_time_out = True
            while int(time.time()) - int(start_time) < 20:
                mic = self.d(resourceId="com.heytap.camera.gwell:id/btn_select_call")
                if mic.exists():
                    if mic.info['clickable']:
                        end_time = time.time()
                        total_time = end_time - start_time
                        self.write_log(self.log_path, str="第" + str(test_num) + "次测试，监控成功，耗时#" + str(total_time))
                        dingTalk.test_pass(take_time=str(total_time), test_num=test_num)

                        is_time_out = False
                        return True
                    time.sleep(0.05)

            if is_time_out:
                error_info = self.d(resourceId="com.heytap.camera.gwell:id/tv_panel_center_warring")
                if error_info.exists():
                    self.write_log(self.log_path, str="第" + str(test_num) + "次测试，监控超时" + error_info.text)
                dingTalk.test_fail(test_num=test_num, info=error_info.text)
            return False
        except Exception as e:
            print(e)
            return False


class DingMessage:
    def __init__(self):
        self.URL = "https://oapi.dingtalk.com/robot/send" \
                   "?access_token=548af9bb73a4e2d13dcdad613a015163d8bc95d9a8474f8fb0ffced5fd77cb3b"  # Webhook地址

        self.headers = {'Content-Type': 'application/json'}

    def test_fail(self, test_num, info):
        data_dict = {
            "msgtype": "markdown",
            "markdown": {
                "title": "监控压力测试异常提示",
                "text": "#### **<font color=#FF0000>第" + str(test_num) + "次测试异常,错误信息： " + info + "**</font>\n\n"
            }
        }
        json_data = json.dumps(data_dict)
        requests.post(self.URL, data=json_data, headers=self.headers, timeout=3)

    def test_pass(self, test_num, take_time):
        data_dict = {
            "msgtype": "markdown",
            "markdown": {
                "title": "监控压力测试通过提示",
                "text": "#### **<font color=#7CFCOO>第" + str(test_num)
                        + "次测试通过**</font>\n\n""> **升级消耗时长:** <font color=#000000>"
                        + str(take_time) + "</font>\n\n"
            }
        }
        json_data = json.dumps(data_dict)
        requests.post(self.URL, data=json_data, headers=self.headers, timeout=3)


if __name__ == '__main__':
    test_time = int(input("请输入测试次数："))
    mo = monitor(devices_name="0.0.0.0", packageName='com.heytap.smarthome')

    count = 1
    while count < test_time + 1:
        mo.set_up()
        if mo.start_monitor(test_num=count):
            count += 1

